<template>
  <cu-layout title="提交订单">
    <view class="p-10" @click="goAddress">
      <view class="cu-card">
        <view class="flex-a ">
          <view class="iconfont icon-zuobiao text-20 text-primary" />
          <view class="flex-1 px-10">
            <view v-if="state.consignee" class="">
              <view class="flex-a">
                <view v-if="state.consignee.is_def" class="tag">
                  默认
                </view>
                <view class="text-15 ">
                  {{ state.consignee.consignee }} {{ state.consignee.phone }}
                </view>
              </view>
              <view class="text-13 text-content mt-4">
                {{ state.consignee.area_name.replaceAll('-', ' ') }} {{ state.consignee.address }}
              </view>
            </view>
            <view v-else class="text-16 text-tips">点击选择收货地址</view>
          </view>
          <view class="iconfont icon-xiangyou1 text-tips text-14" />
        </view>
      </view>
      <view class="cu-card">
        <view class="flex-ba py-5">
          <view class="text-16">商品清单</view>
          <view class="">
            <text class="">种类<text class="text-primary font-600 ml-3">{{ state.cart.product_num }}</text></text>
            <text class="ml-10">数量<text class="text-primary font-600 ml-3">{{ state.cart.total_num }}</text></text>
          </view>
        </view>
        <view class="">
          <view v-for="(item, i) in state.cart.list" :key="item.id" class="py-12 hair-b">
            <view class="flex">
              <view class="flex-shrink rounded-4 overflow-hidden hair-s bg-fa">
                <image class="block" :style="$.utils.getSize(80)" :src="item.sku_logo" mode="" />
              </view>
              <view class="flex-1 flex-vb ml-10">
                <view class="">
                  <view class="ellipsis-2 text-15">{{ item.product_name }}</view>
                  <view class="ellipsis-1 text-13 text-tips my-5">{{ item.sku_name }}</view>
                </view>
                <view class="flex-b">
                  <cu-price class="text-primary" :value="item.retail_price" />
                </view>
              </view>
            </view>
            <view class="mt-10 flex leading-20 ">
              <view class="flex-shrink text-tips">备注:</view>
              <view class="flex-1 ellipsis-2 px-10 text-content">{{ item.remark }}</view>
              <view class="iconfont icon-xiugai text-primary" @click.stop="openRemark(item)" />
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="cu-footer cu-footer-large">
      <view class="cu-footer-fixed flex-ba px-20">
        <view class="">应付： <cu-price class="text-primary" font-size="20" :value="state.cart.total_amount" /> </view>
        <view class="">
          <u-button size="large" shape="circle" type="primary" color="linear-gradient(to right, #3c9cff, #398ade)" @click="save">
            <view class="px-5">提交订单</view>
          </u-button>
        </view>
      </view>
    </view>

    <!-- <u-popup round="8" :show="state.showRemark" mode="center" closeable @close="state.showRemark = false">
      <view class="p-15">
        <view class="text-16 mb-12">备注</view>
        <view class="cu-textarea" style="width: 560rpx;">
          <textarea v-model="state.remark" auto-focus maxlength="500" />
        </view>
        <view class="flex mt-20">
          <view class="flex-1"><u-button text="取消" @click="state.showRemark = false" /></view>
          <view class="flex-1 ml-12"><u-button type="primary" text="保存" @click="remarkSave" /></view>
        </view>
      </view>
    </u-popup> -->

    <cu-cart-remark v-model:show="remark.show" :text="remark.text" :current="remark.id" @done="remarkDone" />
  </cu-layout>
</template>

<script setup>
import {
  reactive
} from 'vue'
import {
  onLoad
} from '@dcloudio/uni-app'
import $ from '@/sheep'
const state = reactive({
  ids: [],
  cart: {
    product_num: 0,
    total_amount: 0,
    total_num: 0,
    list: []
  },
  consignee: null,
  loading: false,
  orderId: 0
})

const remark = reactive({
  id: 0,
  text: '',
  show: false
})

onLoad((options = {}) => {
  state.ids = options.ids.split(',')
  reload()
})

function reload() {
  $.post('/Store/preSubmitOrder', { ids: state.ids }, { isShop: 1 }).then(res => {
    if (res.success) {
      state.cart = res.data.cart
      if (res.data.consignee?.id) {
        state.consignee = res.data.consignee
      }
    } else {
      $.utils.showModal({
        showCancel: false,
        content: res.msg
      }).then(() => {
        $.router.redirect('/pages/cart/index')
      })
    }
  })
}

async function pay() {
  const payRes = await $.post('/Order/pay', { order_id: state.orderId }, { isShop: 1 })

  $.utils.wxpay(payRes.data).then(res => {
    $.utils.tips({ title: '支付成功' }, { tab: 5, url: '/pages/order/index' })
  }, () => {
    $.utils.showModal({
      title: '提示',
      content: '订单支付失败，是否重新发起支付？'
    }).then(res2 => {
      if (res2.confirm) {
        pay()
      } else {
        $.router.redirect('/pages/order/index')
      }
    })
  })
}

async function save() {
  if (state.orderId) {
    return pay()
  }
  // if (!state.consignee) {
  //   return $.utils.toast('请选择收货地址')
  // }
  if (state.loading) return
  state.loading = true
  const orderRes = await $.post('/Store/submitOrder', { ids: state.ids, consignee_id: state.consignee ? state.consignee.id : 0 }, { isShop: 1 })
  state.loading = false
  if (!orderRes.success) {
    return $.utils.toast(orderRes.msg)
  }
  state.orderId = orderRes.data.order_id

  pay()
}

function getAddressInfo(id) {
  $.get('/User/consigneeDetail', { id }).then(res => {
    if (res.success)
      state.consignee = res.data
  })
}

function goAddress() {
  if (state.orderId) {
    return $.utils.toast('提交已订单, 无法修改地址')
  }
  const consigneeId = state.consignee ? state.consignee.id : 0
  $.router.go('/pages/user/address', { current: consigneeId, isSelect: 1 })
  uni.$once('selectAddress', function(data) {
    if (data.id) {
      getAddressInfo(data.id)
    } else {
      state.consignee = null
    }
  })
}

function openRemark(data) {
  remark.id = data.id
  remark.text = data.remark
  remark.show = true
}

function remarkDone(data) {
  const index = state.cart.list.findIndex(v => v.id === data.id)
  state.cart.list[index].remark = data.remark
}

</script>

<style lang="scss">
.tag {
	background-color: $u-primary;
	height: 36rpx;
	line-height: 36rpx;
	color: #fff;
	border-radius: 8rpx;
	font-size: 20rpx;
	padding: 0 10rpx;
	margin-right: 6rpx;
	text-align: center;
}
</style>
